package demo1;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoService {
    DatagramSocket socket;
    public UdpEchoService(Integer  port) throws SocketException {
        //构建一个网卡 后续通过这个网卡来接收发送数据
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动成功");
        while (true) {
            //1.接收请求
            //new 一个数据报来接收数据
            DatagramPacket requestPacket = new DatagramPacket(new byte[4024], 4024);
            socket.receive(requestPacket);
            //2. 处理请求
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            System.out.println("服务器收到:" + request);
            String response = process(request);
            //3.返回响应
            System.out.println("服务器响应:" + response);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), 0, response.getBytes().length,requestPacket.getAddress(), requestPacket.getPort());
            socket.send(responsePacket);
        }
    }

    private String process(String request) {
        //回显服务器
        return request;
    }

    static void main() {
        try {
            UdpEchoService service = new UdpEchoService(9090);
            service.start();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
